# encoding=utf-8

import os

import pandas as pd
from config import config
from core.common import get_strategy_data


def execute_strategy():
    """执行策略"""
    strategy_data_df = get_strategy_data()
    for _, one_strategy_df in strategy_data_df.iterrows():
        if not one_strategy_df['is_need']:
            continue
        strategy_path = os.path.join(config.REPORT_PATH, one_strategy_df['describe'], one_strategy_df['period'])
        os.makedirs(strategy_path, exist_ok=True)
        func = globals()[one_strategy_df['strategy']]
        func(one_strategy_df)


def pure_bond_rapid_growth(one_strategy_df):
    """
    纯债快速增长
    :param one_strategy_df:
    :return:
    """
    screening_pure_bond_rapid_growth(one_strategy_df)
    execute_pure_bond_rapid_growth(one_strategy_df)
    pass


def etf_rapid_growth(one_strategy_df):
    """
    ETF快速增长
    :param one_strategy_df:
    :return:
    """
    execute_etf_rapid_growth(one_strategy_df)
    pass


def stock_rapid_growth(one_strategy_df):
    """
    ETF快速增长
    :param one_strategy_df:
    :return:
    """
    execute_stock_rapid_growth(one_strategy_df)
    pass

def pure_bond_rapid_growth_enhance(one_strategy_df):
    """
    纯债快速增长增强
    :param one_strategy_df:
    :return:
    """
    execute_pure_bond_rapid_growth_enhance(one_strategy_df)
    pass


def pure_bond_choose_excellent(one_strategy_df):
    """
    纯债折优买入
    :param one_strategy_df:
    :return:
    """
    execute_pure_bond_choose_excellent(one_strategy_df)
    pass


def etf_choose_excellent(one_strategy_df):
    """
    ETF折优买入
    :param one_strategy_df:
    :return:
    """
    execute_etf_choose_excellent(one_strategy_df)
    pass


def active_bond_pullback_buy(one_strategy_df):
    """
    积极债回撤买入
    :param one_strategy_df:
    :return:
    """
    screening_active_bond_pullback_buy(one_strategy_df)
    execute_active_bond_pullback_buy(one_strategy_df)
    pass


def screening_pure_bond_rapid_growth(one_strategy_df):
    """
    筛选纯债快速增长
    :param one_strategy_df:
    :return:
    """
    strategy_path = os.path.join(config.REPORT_PATH, one_strategy_df['describe'], one_strategy_df['period'])
    bond_path = os.path.join(config.STRATEGY_PATH, f'{one_strategy_df["data_file_name"]}.xlsx')

    bond_df = pd.read_excel(bond_path, dtype={'code': str})
    buy_all_list = []
    for _, item in bond_df.iterrows():
        if not item['is_need']:
            continue
        file_name = f'{item["code"]}_{item["describe"]}.xlsx'
        file_path = os.path.join(config.COOKED_PATH, item['cate_type'], one_strategy_df['period'], file_name)
        if not os.path.isfile(file_path):
            continue
        df_data = pd.read_excel(file_path, dtype={'code': str})
        buy_one_list = strategy_screening(df_data, item, 'MA2_diff')
        buy_all_list.extend(buy_one_list)

    pd_data = pd.DataFrame(buy_all_list)
    operation_path = os.path.join(strategy_path, '筛选操作记录.xlsx')
    pd_data.to_excel(operation_path, index=False)

    group_data = pd_data.groupby('买入类型').agg({'持有天数': 'mean', '收益率': 'mean', '卖出时间': 'count'}).rename(columns={'持有天数': '平均持有天数', '收益率': '平均收益率', '卖出时间': '数量'})
    group_data['年收益'] = round(group_data['平均收益率'] / group_data['平均持有天数'] * 365, 4)
    group_data['平均持有天数'] = round(group_data['平均持有天数'], 2)
    group_data['平均收益率'] = round(group_data['平均收益率'], 4)
    group_data.to_excel(os.path.join(strategy_path, '筛选操作记录按类型统计.xlsx'))

    group_data = pd_data.groupby(['买入类型', 'code']).agg({'持有天数': 'mean', '收益率': 'mean', '卖出时间': 'count'}).rename(columns={'持有天数': '平均持有天数', '收益率': '平均收益率', '卖出时间': '数量'})
    group_data['年收益'] = round(group_data['平均收益率'] / group_data['平均持有天数'] * 365, 4)
    group_data['平均持有天数'] = round(group_data['平均持有天数'], 2)
    group_data['平均收益率'] = round(group_data['平均收益率'], 4)
    group_data.to_excel(os.path.join(strategy_path, '筛选操作记录按类型和基金统计.xlsx'))

    pd_data['年份'] = pd.to_datetime(pd_data['买入时间']).dt.year
    group_data = pd_data.groupby(['年份', '买入类型']).agg({'持有天数': 'mean', '收益率': 'mean', '卖出时间': 'count'}).rename(columns={'持有天数': '平均持有天数', '收益率': '平均收益率', '卖出时间': '数量'})
    group_data['年收益'] = round(group_data['平均收益率'] / group_data['平均持有天数'] * 365, 4)
    group_data['平均持有天数'] = round(group_data['平均持有天数'], 2)
    group_data['平均收益率'] = round(group_data['平均收益率'], 4)
    group_data.to_excel(os.path.join(strategy_path, '筛选操作记录按年份和类型统计.xlsx'))


def execute_pure_bond_rapid_growth(one_strategy_df):
    """
    执行纯债快速增长
    :param one_strategy_df:
    :return:
    """
    strategy_path = os.path.join(config.REPORT_PATH, one_strategy_df['describe'], one_strategy_df['period'])
    bond_path = os.path.join(config.STRATEGY_PATH, f'{one_strategy_df["data_file_name"]}.xlsx')
    bond_df = pd.read_excel(bond_path, dtype={'code': str})

    operation_path = os.path.join(strategy_path, '操作记录.xlsx')
    if os.path.isfile(operation_path):
        operate_df = pd.read_excel(operation_path, dtype={'code': str})
    else:
        operate_df = pd.DataFrame(columns=['code', '开始时间', '关注时间', '关注天数', '结束时间', '历史最大回撤', '买入时间',
                                            '买入金额', '买入数量', '买入单位净值', '买入累计净值', '卖出时间', '卖出单位净值',
                                            '卖出累计净值', '持有天数', '收益', '收益率', '分仓'])

    account_path = os.path.join(strategy_path, '策略账户.xlsx')
    if os.path.isfile(account_path):
        account_df = pd.read_excel(account_path)
    else:
        account_df = pd.DataFrame([{'日期': one_strategy_df['start_time'],
                                    '策略': one_strategy_df['strategy'],
                                    '总资产': 500000,
                                    '现金余额': 500000,
                                    '持仓市值': 0,
                                    '持仓成本': 0,
                                    '持仓盈亏': 0,
                                    '持仓数量': 0}])

    start_time = account_df['日期'].max() + pd.Timedelta(days=1)
    end_time = pd.Timestamp('now').date()
    bond_data_dict = get_bond_data(bond_df, one_strategy_df)
    buy_rate = 1

    for current_time in pd.date_range(start=start_time, end=end_time, freq='D'):
        current_money = account_df.tail(1).iloc[0]['现金余额']
        last_day_money = account_df.tail(1).iloc[0]['总资产']

        # 获取当天价格
        current_day_bond_data_df = get_current_day_bond_data(bond_df, bond_data_dict, current_time)
        if current_day_bond_data_df.empty:
            continue
        # 关注
        operate_df = follow(bond_df, current_day_bond_data_df, operate_df, 'MA2_diff')

        # 卖出
        operate_df, current_money = sell(bond_df, current_day_bond_data_df, operate_df, current_money)

        # 买入
        operate_df, current_money = buy(operate_df, current_day_bond_data_df, current_money, buy_rate, last_day_money)

        # 分仓

        # 更新账户
        account_df = update_account(operate_df, account_df, current_day_bond_data_df, current_time, current_money)

    account_df.to_excel(account_path, index=False)
    operate_df.to_excel(operation_path, index=False)
    # bond_df.to_excel(bond_path, index=False)

    account_df['年份'] = pd.to_datetime(account_df['日期']).dt.year
    group = account_df.groupby('年份').agg({'总资产': 'last'})
    group['增长率'] = group['总资产'] / group['总资产'].shift(1)
    print(group)


def execute_etf_rapid_growth(one_strategy_df):
    """
    执行纯etf速增长
    :param one_strategy_df:
    :return:
    """
    strategy_path = os.path.join(config.REPORT_PATH, one_strategy_df['describe'], one_strategy_df['period'])
    bond_path = os.path.join(config.STRATEGY_PATH, f'{one_strategy_df["data_file_name"]}.xlsx')
    bond_df = pd.read_excel(bond_path, dtype={'code': str})

    operation_path = os.path.join(strategy_path, '操作记录.xlsx')
    if os.path.isfile(operation_path):
        operate_df = pd.read_excel(operation_path, dtype={'code': str})
    else:
        operate_df = pd.DataFrame(columns=['code', '开始时间', '关注时间', '关注天数', '结束时间', '历史最大回撤', '买入时间',
                                            '买入金额', '买入数量', '买入单位净值', '买入累计净值', '卖出时间', '卖出单位净值',
                                            '卖出累计净值', '持有天数', '收益', '收益率', '分仓'])

    account_path = os.path.join(strategy_path, '策略账户.xlsx')
    if os.path.isfile(account_path):
        account_df = pd.read_excel(account_path)
    else:
        account_df = pd.DataFrame([{'日期': one_strategy_df['start_time'],
                                    '策略': one_strategy_df['strategy'],
                                    '总资产': 500000,
                                    '现金余额': 500000,
                                    '持仓市值': 0,
                                    '持仓成本': 0,
                                    '持仓盈亏': 0,
                                    '持仓数量': 0}])

    start_time = account_df['日期'].max() + pd.Timedelta(days=1)
    end_time = pd.Timestamp('now').date()
    bond_data_dict = get_bond_data(bond_df, one_strategy_df)
    buy_rate = 1

    for current_time in pd.date_range(start=start_time, end=end_time, freq='D'):
        current_money = account_df.tail(1).iloc[0]['现金余额']
        last_day_money = account_df.tail(1).iloc[0]['总资产']

        # 获取当天价格
        current_day_bond_data_df = get_current_day_bond_data(bond_df, bond_data_dict, current_time)
        if current_day_bond_data_df.empty:
            continue
        # 关注
        operate_df = follow(bond_df, current_day_bond_data_df, operate_df, 'MA2_diff')

        # 卖出
        operate_df, current_money = sell(bond_df, current_day_bond_data_df, operate_df, current_money)

        # 买入
        operate_df, current_money = buy(operate_df, current_day_bond_data_df, current_money, buy_rate, last_day_money)

        # 分仓

        # 更新账户
        account_df = update_account(operate_df, account_df, current_day_bond_data_df, current_time, current_money)

    account_df.to_excel(account_path, index=False)
    operate_df.to_excel(operation_path, index=False)
    # bond_df.to_excel(bond_path, index=False)

    account_df['年份'] = pd.to_datetime(account_df['日期']).dt.year
    group = account_df.groupby('年份').agg({'总资产': 'last'})
    group['增长率'] = group['总资产'] / group['总资产'].shift(1)
    print(group)


def execute_stock_rapid_growth(one_strategy_df):
    """
    执行股票快速增长
    :param one_strategy_df:
    :return:
    """
    strategy_path = os.path.join(config.REPORT_PATH, one_strategy_df['describe'], one_strategy_df['period'])
    bond_path = os.path.join(config.STRATEGY_PATH, f'{one_strategy_df["data_file_name"]}.xlsx')
    bond_df = pd.read_excel(bond_path, dtype={'code': str})

    operation_path = os.path.join(strategy_path, '操作记录.xlsx')
    if os.path.isfile(operation_path):
        operate_df = pd.read_excel(operation_path, dtype={'code': str})
    else:
        operate_df = pd.DataFrame(
            columns=['code', '开始时间', '关注时间', '关注天数', '结束时间', '历史最大回撤', '买入时间',
                     '买入金额', '买入数量', '买入单位净值', '买入累计净值', '卖出时间', '卖出单位净值',
                     '卖出累计净值', '持有天数', '收益', '收益率', '分仓'])

    account_path = os.path.join(strategy_path, '策略账户.xlsx')
    if os.path.isfile(account_path):
        account_df = pd.read_excel(account_path)
    else:
        account_df = pd.DataFrame([{'日期': one_strategy_df['start_time'],
                                    '策略': one_strategy_df['strategy'],
                                    '总资产': 500000,
                                    '现金余额': 500000,
                                    '持仓市值': 0,
                                    '持仓成本': 0,
                                    '持仓盈亏': 0,
                                    '持仓数量': 0}])

    start_time = account_df['日期'].max() + pd.Timedelta(days=1)
    end_time = pd.Timestamp('now').date()
    bond_data_dict = get_bond_data(bond_df, one_strategy_df)
    buy_rate = 1

    for current_time in pd.date_range(start=start_time, end=end_time, freq='D'):
        current_money = account_df.tail(1).iloc[0]['现金余额']
        last_day_money = account_df.tail(1).iloc[0]['总资产']

        # 获取当天价格
        current_day_bond_data_df = get_current_day_bond_data(bond_df, bond_data_dict, current_time)
        if current_day_bond_data_df.empty:
            continue
        # 关注
        operate_df = follow(bond_df, current_day_bond_data_df, operate_df, 'MA2_diff')

        # 卖出
        operate_df, current_money = sell(bond_df, current_day_bond_data_df, operate_df, current_money)

        # 买入
        operate_df, current_money = buy(operate_df, current_day_bond_data_df, current_money, buy_rate,
                                        last_day_money)

        # 分仓

        # 更新账户
        account_df = update_account(operate_df, account_df, current_day_bond_data_df, current_time, current_money)

    account_df.to_excel(account_path, index=False)
    operate_df.to_excel(operation_path, index=False)
    # bond_df.to_excel(bond_path, index=False)

    account_df['年份'] = pd.to_datetime(account_df['日期']).dt.year
    group = account_df.groupby('年份').agg({'总资产': 'last'})
    group['增长率'] = group['总资产'] / group['总资产'].shift(1)
    print(group)


def execute_pure_bond_rapid_growth_enhance(one_strategy_df):
    """
    执行纯债快速增长
    :param one_strategy_df:
    :return:
    """
    strategy_path = os.path.join(config.REPORT_PATH, one_strategy_df['describe'], one_strategy_df['period'])
    bond_path = os.path.join(config.STRATEGY_PATH, f'{one_strategy_df["data_file_name"]}.xlsx')
    bond_df = pd.read_excel(bond_path, dtype={'code': str})

    operation_path = os.path.join(strategy_path, '操作记录.xlsx')
    if os.path.isfile(operation_path):
        operate_df = pd.read_excel(operation_path, dtype={'code': str})
    else:
        operate_df = pd.DataFrame(columns=['code', '开始时间', '关注时间', '关注天数', '结束时间', '历史最大回撤', '买入时间',
                                            '买入金额', '买入数量', '买入单位净值', '买入累计净值', '卖出时间', '卖出单位净值',
                                            '卖出累计净值', '持有天数', '收益', '收益率', '分仓', 'period', '大于预期', '小于预期'])

    account_path = os.path.join(strategy_path, '策略账户.xlsx')
    if os.path.isfile(account_path):
        account_df = pd.read_excel(account_path)
    else:
        account_df = pd.DataFrame([{'日期': one_strategy_df['start_time'],
                                    '策略': one_strategy_df['strategy'],
                                    '总资产': 500000,
                                    '现金余额': 500000,
                                    '持仓市值': 0,
                                    '持仓成本': 0,
                                    '持仓盈亏': 0,
                                    '持仓数量': 0}])

    start_time = account_df['日期'].max() + pd.Timedelta(days=1)
    end_time = pd.Timestamp('now').date()
    bond_data_dict = get_bond_data(bond_df, one_strategy_df)
    buy_rate = 1

    for current_time in pd.date_range(start=start_time, end=end_time, freq='D'):
        current_money = account_df.tail(1).iloc[0]['现金余额']
        last_day_money = account_df.tail(1).iloc[0]['总资产']

        # 获取当天价格
        current_day_bond_data_df = get_current_day_bond_data(bond_df, bond_data_dict, current_time)
        if current_day_bond_data_df.empty:
            continue
        # 关注
        operate_df = follow_rapid_growth_enhance(bond_df, current_day_bond_data_df, operate_df, 'MA1_diff')

        # 卖出
        operate_df, current_money = sell(bond_df, current_day_bond_data_df, operate_df, current_money)

        # 买入
        operate_df, current_money = buy(operate_df, current_day_bond_data_df, current_money, buy_rate, last_day_money)

        # 更新账户
        account_df = update_account(operate_df, account_df, current_day_bond_data_df, current_time, current_money)

    account_df.to_excel(account_path, index=False)
    operate_df.to_excel(operation_path, index=False)
    # bond_df.to_excel(bond_path, index=False)

    account_df['年份'] = pd.to_datetime(account_df['日期']).dt.year
    group = account_df.groupby('年份').agg({'总资产': 'last'})
    group['增长率'] = group['总资产'] / group['总资产'].shift(1)
    print(group)


def execute_pure_bond_choose_excellent(one_strategy_df):
    """
    执行纯债折优买入
    :param one_strategy_df:
    :return:
    """
    strategy_path = os.path.join(config.REPORT_PATH, one_strategy_df['describe'], one_strategy_df['period'])
    bond_path = os.path.join(config.STRATEGY_PATH, f'{one_strategy_df["data_file_name"]}.xlsx')
    bond_df = pd.read_excel(bond_path, dtype={'code': str})

    operation_path = os.path.join(strategy_path, '操作记录.xlsx')
    if os.path.isfile(operation_path):
        operate_df = pd.read_excel(operation_path, dtype={'code': str})
    else:
        operate_df = pd.DataFrame(columns=['code', '开始时间', '关注时间', '关注天数', '结束时间', '历史最大回撤', '买入时间',
                                            '买入金额', '买入数量', '买入单位净值', '买入累计净值', '卖出时间', '卖出单位净值',
                                            '卖出累计净值', '持有天数', '收益', '收益率', '分仓'])

    account_path = os.path.join(strategy_path, '策略账户.xlsx')
    if os.path.isfile(account_path):
        account_df = pd.read_excel(account_path)
    else:
        account_df = pd.DataFrame([{'日期': one_strategy_df['start_time'],
                                    '策略': one_strategy_df['strategy'],
                                    '总资产': 500000,
                                    '现金余额': 500000,
                                    '持仓市值': 0,
                                    '持仓成本': 0,
                                    '持仓盈亏': 0,
                                    '持仓数量': 0}])

    start_time = account_df['日期'].max() + pd.Timedelta(days=1)
    end_time = pd.Timestamp('now').date()
    bond_data_dict = get_bond_data(bond_df, one_strategy_df)
    buy_rate = 1 / 3

    for current_time in pd.date_range(start=start_time, end=end_time, freq='D'):
        current_money = account_df.tail(1).iloc[0]['现金余额']
        last_day_money = account_df.tail(1).iloc[0]['总资产']
        last_month = pd.to_datetime(account_df.tail(1).iloc[0]['日期']).month

        # 获取当天价格
        current_day_bond_data_df = get_current_day_bond_data(bond_df, bond_data_dict, current_time)
        if current_day_bond_data_df.empty:
            continue

        if pd.to_datetime(current_time).month != last_month:
            # 关注
            operate_df = follow_choose_excellent(bond_df, current_day_bond_data_df, operate_df, 'MA2_diff')

        # 卖出
        operate_df, current_money = sell(bond_df, current_day_bond_data_df, operate_df, current_money)

        # 买入
        operate_df, current_money = buy_no_buy(operate_df, current_day_bond_data_df, current_money, buy_rate, last_day_money)

        # 更新账户
        account_df = update_account(operate_df, account_df, current_day_bond_data_df, current_time, current_money)

    account_df.to_excel(account_path, index=False)
    operate_df.to_excel(operation_path, index=False)
    # bond_df.to_excel(bond_path, index=False)

    account_df['年份'] = pd.to_datetime(account_df['日期']).dt.year
    group = account_df.groupby('年份').agg({'总资产': 'last'})
    group['增长率'] = group['总资产'] / group['总资产'].shift(1)
    print(group)


def execute_etf_choose_excellent(one_strategy_df):
    """
    执行ETF折优买入
    :param one_strategy_df:
    :return:
    """
    strategy_path = os.path.join(config.REPORT_PATH, one_strategy_df['describe'], one_strategy_df['period'])
    bond_path = os.path.join(config.STRATEGY_PATH, f'{one_strategy_df["data_file_name"]}.xlsx')
    bond_df = pd.read_excel(bond_path, dtype={'code': str})

    operation_path = os.path.join(strategy_path, '操作记录.xlsx')
    if os.path.isfile(operation_path):
        operate_df = pd.read_excel(operation_path, dtype={'code': str})
    else:
        operate_df = pd.DataFrame(columns=['code', '开始时间', '关注时间', '关注天数', '结束时间', '历史最大回撤', '买入时间',
                                            '买入金额', '买入数量', '买入单位净值', '买入累计净值', '卖出时间', '卖出单位净值',
                                            '卖出累计净值', '持有天数', '收益', '收益率', '分仓'])

    account_path = os.path.join(strategy_path, '策略账户.xlsx')
    if os.path.isfile(account_path):
        account_df = pd.read_excel(account_path)
    else:
        account_df = pd.DataFrame([{'日期': one_strategy_df['start_time'],
                                    '策略': one_strategy_df['strategy'],
                                    '总资产': 500000,
                                    '现金余额': 500000,
                                    '持仓市值': 0,
                                    '持仓成本': 0,
                                    '持仓盈亏': 0,
                                    '持仓数量': 0}])

    start_time = account_df['日期'].max() + pd.Timedelta(days=1)
    end_time = pd.Timestamp('now').date()
    bond_data_dict = get_bond_data(bond_df, one_strategy_df)
    buy_rate = 1 / 3

    for current_time in pd.date_range(start=start_time, end=end_time, freq='D'):
        current_money = account_df.tail(1).iloc[0]['现金余额']
        last_day_money = account_df.tail(1).iloc[0]['总资产']
        last_month = pd.to_datetime(account_df.tail(1).iloc[0]['日期']).month

        # 获取当天价格
        current_day_bond_data_df = get_current_day_bond_data(bond_df, bond_data_dict, current_time)
        if current_day_bond_data_df.empty:
            continue

        if pd.to_datetime(current_time).month != last_month:
            # 关注
            operate_df = follow_choose_excellent(bond_df, current_day_bond_data_df, operate_df, 'MA2_diff')

        # 卖出
        operate_df, current_money = sell(bond_df, current_day_bond_data_df, operate_df, current_money)

        # 买入
        operate_df, current_money = buy_no_buy(operate_df, current_day_bond_data_df, current_money, buy_rate, last_day_money)

        # 更新账户
        account_df = update_account(operate_df, account_df, current_day_bond_data_df, current_time, current_money)

    account_df.to_excel(account_path, index=False)
    operate_df.to_excel(operation_path, index=False)
    # bond_df.to_excel(bond_path, index=False)

    account_df['年份'] = pd.to_datetime(account_df['日期']).dt.year
    group = account_df.groupby('年份').agg({'总资产': 'last'})
    group['增长率'] = group['总资产'] / group['总资产'].shift(1)
    print(group)


def screening_active_bond_pullback_buy(one_strategy_df):
    """
    筛选积极债回撤买入
    :param one_strategy_df:
    :return:
    """
    strategy_path = os.path.join(config.REPORT_PATH, one_strategy_df['describe'], one_strategy_df['period'])
    bond_path = os.path.join(config.STRATEGY_PATH, f'{one_strategy_df["data_file_name"]}.xlsx')

    bond_df = pd.read_excel(bond_path, dtype={'code': str})
    buy_all_list = []
    for _, item in bond_df.iterrows():
        if not item['is_need']:
            continue
        file_name = f'{item["code"]}_{item["describe"]}.xlsx'
        file_path = os.path.join(config.COOKED_PATH, item['cate_type'], one_strategy_df['period'], file_name)
        if not os.path.isfile(file_path):
            continue
        df_data = pd.read_excel(file_path, dtype={'code': str})
        buy_one_list = strategy_screening(df_data, item, 'draw_down')
        buy_all_list.extend(buy_one_list)

    pd_data = pd.DataFrame(buy_all_list)
    operation_path = os.path.join(strategy_path, '筛选操作记录.xlsx')
    pd_data.to_excel(operation_path, index=False)

    group_data = pd_data.groupby('买入类型').agg({'持有天数': 'mean', '收益率': 'mean', '卖出时间': 'count'}).rename(columns={'持有天数': '平均持有天数', '收益率': '平均收益率', '卖出时间': '数量'})
    group_data['年收益'] = round(group_data['平均收益率'] / group_data['平均持有天数'] * 365, 4)
    group_data['平均持有天数'] = round(group_data['平均持有天数'], 2)
    group_data['平均收益率'] = round(group_data['平均收益率'], 4)
    group_data.to_excel(os.path.join(strategy_path, '筛选操作记录按类型统计.xlsx'))

    group_data = pd_data.groupby(['买入类型', 'code']).agg({'持有天数': 'mean', '收益率': 'mean', '卖出时间': 'count'}).rename(columns={'持有天数': '平均持有天数', '收益率': '平均收益率', '卖出时间': '数量'})
    group_data['年收益'] = round(group_data['平均收益率'] / group_data['平均持有天数'] * 365, 4)
    group_data['平均持有天数'] = round(group_data['平均持有天数'], 2)
    group_data['平均收益率'] = round(group_data['平均收益率'], 4)
    group_data.to_excel(os.path.join(strategy_path, '筛选操作记录按类型和基金统计.xlsx'))

    pd_data['年份'] = pd.to_datetime(pd_data['买入时间']).dt.year
    group_data = pd_data.groupby(['年份', '买入类型']).agg({'持有天数': 'mean', '收益率': 'mean', '卖出时间': 'count'}).rename(columns={'持有天数': '平均持有天数', '收益率': '平均收益率', '卖出时间': '数量'})
    group_data['年收益'] = round(group_data['平均收益率'] / group_data['平均持有天数'] * 365, 4)
    group_data['平均持有天数'] = round(group_data['平均持有天数'], 2)
    group_data['平均收益率'] = round(group_data['平均收益率'], 4)
    group_data.to_excel(os.path.join(strategy_path, '筛选操作记录按年份和类型统计.xlsx'))


def execute_active_bond_pullback_buy(one_strategy_df):
    """
    执行积极债回撤买入
    :param one_strategy_df:
    :return:
    """
    strategy_path = os.path.join(config.REPORT_PATH, one_strategy_df['describe'], one_strategy_df['period'])
    bond_path = os.path.join(config.STRATEGY_PATH, f'{one_strategy_df["data_file_name"]}.xlsx')
    bond_df = pd.read_excel(bond_path, dtype={'code': str})

    operation_path = os.path.join(strategy_path, '操作记录.xlsx')
    if os.path.isfile(operation_path):
        operate_df = pd.read_excel(operation_path, dtype={'code': str})
    else:
        operate_df = pd.DataFrame(columns=['code', '开始时间', '关注时间', '关注天数', '结束时间', '历史最大回撤', '买入时间',
                                            '买入金额', '买入数量', '买入单位净值', '买入累计净值', '卖出时间', '卖出单位净值',
                                            '卖出累计净值', '持有天数', '收益', '收益率', '分仓'])

    account_path = os.path.join(strategy_path, '策略账户.xlsx')
    if os.path.isfile(account_path):
        account_df = pd.read_excel(account_path)
    else:
        account_df = pd.DataFrame([{'日期': one_strategy_df['start_time'],
                                    '策略': one_strategy_df['strategy'],
                                    '总资产': 500000,
                                    '现金余额': 500000,
                                    '持仓市值': 0,
                                    '持仓成本': 0,
                                    '持仓盈亏': 0,
                                    '持仓数量': 0}])

    start_time = account_df['日期'].max() + pd.Timedelta(days=1)
    end_time = pd.Timestamp('now').date()
    bond_data_dict = get_bond_data(bond_df, one_strategy_df)
    buy_rate = 1

    for current_time in pd.date_range(start=start_time, end=end_time, freq='D'):
        current_money = account_df.tail(1).iloc[0]['现金余额']
        last_day_money = account_df.tail(1).iloc[0]['总资产']

        # 获取当天价格
        current_day_bond_data_df = get_current_day_bond_data(bond_df, bond_data_dict, current_time)
        if current_day_bond_data_df.empty:
            continue
        # 关注
        operate_df = follow(bond_df, current_day_bond_data_df, operate_df, 'draw_down')

        # 卖出
        operate_df, current_money = sell(bond_df, current_day_bond_data_df, operate_df, current_money)

        # 买入
        operate_df, current_money = buy(operate_df, current_day_bond_data_df, current_money, buy_rate, last_day_money)

        # 分仓
        operate_df = divide_by_time(operate_df, current_day_bond_data_df, current_time)

        # 更新账户
        account_df = update_account(operate_df, account_df, current_day_bond_data_df, current_time, current_money)

    account_df.to_excel(account_path, index=False)
    operate_df.to_excel(operation_path, index=False)
    # bond_df.to_excel(bond_path, index=False)

    account_df['年份'] = pd.to_datetime(account_df['日期']).dt.year
    group = account_df.groupby('年份').agg({'总资产': 'last'})
    group['增长率'] = group['总资产'] / group['总资产'].shift(1)
    print(group)


def strategy_screening(df_data, bond_dict, key_name):
    last_buy_point = 0  # 上一次买入点
    buy_all_list = []

    for _, row in df_data.iterrows():
        if row[key_name] <= bond_dict['sell_point']:
            [item.update({
                '日期': row['净值日期'],
                '卖出时间': row['净值日期'],
                '卖出单位净值': row['单位净值'],
                '卖出累计净值': row['累计净值'],
                '持有天数': (row['净值日期'] - item['买入时间']).days,
                '收益率': round((row['累计净值'] - item['买入累计净值']) / item['买入单位净值'], 4),
                '年收益': round((row['累计净值'] - item['买入累计净值']) / item['买入单位净值'] / (row['净值日期'] - item['买入时间']).days * 365, 4)
            }) for item in buy_all_list if item['code'] == bond_dict['code'] and item['卖出时间'] is None]
            last_buy_point = 0
        if row[key_name] >= bond_dict['low_buy_point']:
            current_buy_point = int(row[key_name] / bond_dict['interval'])
            point_range = range(max(int(bond_dict['low_buy_point'] / bond_dict['interval']), last_buy_point + 1), current_buy_point + 1)
            for key in point_range:
                if not [item for item in buy_all_list if item['code'] == bond_dict['code'] and item['买入类型'] == key and item['卖出时间'] is None]:
                    buy_all_list.append({
                        '日期': row['净值日期'],
                        'code': bond_dict['code'],
                        '买入时间': row['净值日期'],
                        '买入类型': key,
                        '买入金额': None,
                        '买入数量': None,
                        '买入单位净值': row['单位净值'],
                        '买入累计净值': row['累计净值'],
                        '卖出时间': None,
                        '卖出单位净值': None,
                        '卖出累计净值': None,
                        '持有天数': None,
                        '收益率': None,
                        '年收益': None
                    })
                last_buy_point = key
    return buy_all_list


def get_bond_data(bond_df, one_strategy_df):
    bond_data_dict = {}
    for _, item in bond_df.iterrows():
        if not item['is_need']:
            continue
        file_name = f'{item["code"]}_{item["describe"]}.xlsx'
        file_path = os.path.join(config.COOKED_PATH, item['cate_type'], one_strategy_df['period'], file_name)
        if not os.path.isfile(file_path):
            continue
        df_data = pd.read_excel(file_path, dtype={'code': str})
        code = item['code']
        bond_data_dict.update({
            code: df_data
        })
    return bond_data_dict


def get_current_day_bond_data(bond_df, bond_data_dict, current_time):
    current_day_bond_data_df = pd.DataFrame()
    for _, item in bond_df.iterrows():
        # if current_time <= item['operate_time']:
        #     continue
        bond_data_df = bond_data_dict.get(item["code"], pd.DataFrame())
        if bond_data_df.empty:
            continue
        one_day_bond_data_df = bond_data_df.loc[bond_data_df['净值日期'] == current_time]
        if one_day_bond_data_df.empty:
            continue
        # one_day_bond_data = one_day_bond_data_df.iloc[0]
        if current_day_bond_data_df.empty:
            current_day_bond_data_df = one_day_bond_data_df
        else:
            current_day_bond_data_df = pd.concat([current_day_bond_data_df, one_day_bond_data_df]).reset_index(drop=True)
    return current_day_bond_data_df


def follow(bond_df, current_day_bond_data_df, operate_df, key_name):
    for _, item in bond_df.iterrows():
        one_day_bond_data_df = current_day_bond_data_df.loc[current_day_bond_data_df['code'] == item["code"]]
        if one_day_bond_data_df.empty:
            continue
        one_day_bond_data = one_day_bond_data_df.iloc[0]
        if one_day_bond_data[key_name] >= item['buy_point']:
            mask = (operate_df['code'] == item['code']) & (operate_df['结束时间'].isnull())

            if operate_df.loc[mask].empty:
                operate_df = pd.concat([operate_df, pd.DataFrame([{
                    'code': item['code'],
                    '开始时间': one_day_bond_data['净值日期'],
                    '关注时间': one_day_bond_data['净值日期'],
                    '关注天数': None,
                    '结束时间': None,
                    '历史最大回撤': None,
                    '买入时间': None,
                    '买入金额': None,
                    '买入数量': None,
                    '买入单位净值': None,
                    '买入累计净值': None,
                    '卖出时间': None,
                    '卖出单位净值': None,
                    '卖出累计净值': None,
                    '持有天数': None,
                    '收益': None,
                    '收益率': None,
                    '年收益': None,
                    '分仓': '分仓'
                }])]).reset_index(drop=True)
        if one_day_bond_data[key_name] <= item['sell_point']:
            mask = (operate_df['code'] == item['code']) & (operate_df['开始时间'].notnull()) & (
                operate_df['结束时间'].isnull())
            operate_df.loc[mask, '关注天数'] = one_day_bond_data['净值日期'] - operate_df.loc[mask, '关注时间']
            operate_df.loc[mask, '结束时间'] = one_day_bond_data['净值日期']
    return operate_df


def follow_rapid_growth_enhance(bond_df, current_day_bond_data_df, operate_df, key_name):
    mask = (operate_df['买入时间'].notnull()) & (operate_df['结束时间'].isnull())
    filter_df = operate_df.loc[mask]
    for _, item in filter_df.iterrows():
        one_day_bond_data_df = current_day_bond_data_df.loc[current_day_bond_data_df['code'] == item["code"]]
        if one_day_bond_data_df.empty:
            continue
        one_day_bond_data = one_day_bond_data_df.iloc[0]

        one_bond_data_df = bond_df.loc[bond_df['code'] == item["code"]]
        if one_bond_data_df.empty:
            continue
        one_bond_data = one_bond_data_df.iloc[0]

        mask = (operate_df['code'] == item['code']) & (operate_df['买入时间'] == item['买入时间']) & (
                operate_df['买入数量'] == item['买入数量']) & (operate_df['买入金额'] == item['买入金额'])
        operate_df.loc[mask, 'period'] = operate_df.loc[mask, 'period'] + 1
        if one_day_bond_data[key_name] > one_bond_data['buy_point']:
            operate_df.loc[mask, '大于预期'] = operate_df.loc[mask, '大于预期'] + one_day_bond_data[key_name] - one_bond_data['sell_point']
        else:
            operate_df.loc[mask, '小于预期'] = operate_df.loc[mask, '小于预期'] - one_day_bond_data[key_name] + one_bond_data['sell_point']

        if operate_df.loc[mask, '大于预期'].iloc[0] * 0 < operate_df.loc[mask, '小于预期'].iloc[0]:
            operate_df.loc[mask, '关注天数'] = one_day_bond_data['净值日期'] - operate_df.loc[mask, '关注时间']
            operate_df.loc[mask, '结束时间'] = one_day_bond_data['净值日期']

    for _, item in bond_df.iterrows():
        one_day_bond_data_df = current_day_bond_data_df.loc[current_day_bond_data_df['code'] == item["code"]]
        if one_day_bond_data_df.empty:
            continue
        one_day_bond_data = one_day_bond_data_df.iloc[0]
        if one_day_bond_data[key_name] >= item['buy_point']:
            mask = (operate_df['code'] == item['code']) & (operate_df['结束时间'].isnull())

            if operate_df.loc[mask].empty:
                operate_df = pd.concat([operate_df, pd.DataFrame([{
                    'code': item['code'],
                    '开始时间': one_day_bond_data['净值日期'],
                    '关注时间': one_day_bond_data['净值日期'],
                    '关注天数': None,
                    '结束时间': None,
                    '历史最大回撤': one_day_bond_data['history_max_draw_down'],
                    '买入时间': None,
                    '买入金额': None,
                    '买入数量': None,
                    '买入单位净值': None,
                    '买入累计净值': None,
                    '卖出时间': None,
                    '卖出单位净值': None,
                    '卖出累计净值': None,
                    '持有天数': None,
                    '收益': None,
                    '收益率': None,
                    '年收益': None,
                    '分仓': '分仓',
                    'period': 0,
                    '大于预期': 0,
                    '小于预期': 0
                }])]).reset_index(drop=True)
        if one_day_bond_data[key_name] <= item['sell_point']:
            mask = (operate_df['code'] == item['code']) & (operate_df['买入时间'].isnull()) & (
                operate_df['结束时间'].isnull())
            operate_df.loc[mask, '关注天数'] = one_day_bond_data['净值日期'] - operate_df.loc[mask, '关注时间']
            operate_df.loc[mask, '结束时间'] = one_day_bond_data['净值日期']
    return operate_df


def follow_choose_excellent(bond_df, current_day_bond_data_df, operate_df, key_name):
    # 对所有数据进行排序
    current_day_bond_data_df = current_day_bond_data_df.sort_values(by=key_name, ascending=False).reset_index()
    buy_number = 0
    buy_status = False
    for _, ond_bond in current_day_bond_data_df.iterrows():
        mask = (operate_df['code'] == ond_bond['code']) & (operate_df['结束时间'].isnull())
        if operate_df.loc[mask].empty:
            if not buy_status:
                operate_df = pd.concat([operate_df, pd.DataFrame([{
                    'code': ond_bond['code'],
                    '开始时间': ond_bond['净值日期'],
                    '关注时间': ond_bond['净值日期'],
                    '关注天数': None,
                    '结束时间': None,
                    '历史最大回撤': None,
                    '买入时间': None,
                    '买入金额': None,
                    '买入数量': None,
                    '买入单位净值': None,
                    '买入累计净值': None,
                    '卖出时间': None,
                    '卖出单位净值': None,
                    '卖出累计净值': None,
                    '持有天数': None,
                    '收益': None,
                    '收益率': None,
                    '年收益': None,
                    '分仓': '分仓'
                }])]).reset_index(drop=True)
                buy_status = True
                buy_number += 1
        else:
            buy_number += 1

        if buy_number == 4:
            mask = (operate_df['code'] == ond_bond['code']) & (operate_df['开始时间'].notnull()) & (
                operate_df['结束时间'].isnull())
            operate_df.loc[mask, '关注天数'] = ond_bond['净值日期'] - operate_df.loc[mask, '关注时间']
            operate_df.loc[mask, '结束时间'] = ond_bond['净值日期']
    return operate_df


def divide_by_time(operate_df, current_day_bond_data_df, current_time):
    mask = (operate_df['买入时间'].notnull()) & (operate_df['卖出时间'].isnull()) & (operate_df['结束时间'].isnull()) & (operate_df['关注时间'] < current_time - pd.Timedelta(days=180)) & (operate_df['买入时间'] < current_time - pd.Timedelta(days=30))
    buy_filter_df = operate_df.loc[mask]

    for _, item in buy_filter_df.iterrows():
        one_day_bond_data_df = current_day_bond_data_df.loc[current_day_bond_data_df['code'] == item["code"]]
        if one_day_bond_data_df.empty:
            continue
        one_day_bond_data = one_day_bond_data_df.iloc[0]
        if one_day_bond_data['draw_down'] < 0.06:
            continue
        mask = (operate_df['code'] != item['code']) & (operate_df['卖出时间'].isnull()) & (operate_df['结束时间'].isnull()) & (operate_df['关注时间'] > current_time - pd.Timedelta(days=150))
        no_filter_df = operate_df.loc[mask]
        if no_filter_df.empty:
            continue
        for _, no_item in no_filter_df.iterrows():
            no_one_day_bond_data_df = current_day_bond_data_df.loc[current_day_bond_data_df['code'] == no_item["code"]]
            if no_one_day_bond_data_df.empty:
                continue
            no_one_day_bond_data = no_one_day_bond_data_df.iloc[0]
            if no_item['code'] in item['分仓']:
                continue
            # 自己卖出
            if item['分仓'].count('分仓') == 1:
                distribute_rate = 0.3
            elif item['分仓'].count('分仓') == 2:
                distribute_rate = 0.4
            else:
                distribute_rate = 0.5
            mask = (operate_df['code'] == item['code']) & (operate_df['买入时间'] == item['买入时间']) & (
                operate_df['买入数量'] == item['买入数量']) & (operate_df['买入金额'] == item['买入金额'])
            operate_df.loc[mask, '买入数量'] = int(item['买入数量'] * (1 - distribute_rate))
            operate_df.loc[mask, '买入金额'] = int(item['买入数量'] * (1 - distribute_rate)) * item['买入单位净值']
            operate_df.loc[mask, '分仓'] = item['分仓'] + f'：分仓给{no_item["code"]}'
            # 对方买入
            buy_number = one_day_bond_data['单位净值'] * item['买入数量'] * distribute_rate / no_one_day_bond_data['单位净值']

            if pd.notnull(no_item['买入数量']):
                operate_df = pd.concat([operate_df, pd.DataFrame([{
                    'code': no_item['code'],
                    '开始时间': no_item['开始时间'],
                    '关注时间': no_item['关注时间'],
                    '关注天数': None,
                    '结束时间': None,
                    '历史最大回撤': no_item['历史最大回撤'],
                    '买入时间': None,
                    '买入金额': None,
                    '买入数量': None,
                    '买入单位净值': None,
                    '买入累计净值': None,
                    '卖出时间': None,
                    '卖出单位净值': None,
                    '卖出累计净值': None,
                    '持有天数': None,
                    '收益': None,
                    '收益率': None,
                    '年收益': None,
                    '分仓': f'分仓'
                }])]).reset_index(drop=True)
            mask = (operate_df['code'] == no_item['code']) & (operate_df['买入时间'].isnull()) & (operate_df['卖出时间'].isnull()) & (operate_df['结束时间'].isnull())
            operate_df.loc[mask, '买入时间'] = no_one_day_bond_data['净值日期']
            operate_df.loc[mask, '买入金额'] = no_one_day_bond_data['单位净值'] * buy_number
            operate_df.loc[mask, '买入数量'] = buy_number
            operate_df.loc[mask, '买入单位净值'] = no_one_day_bond_data['单位净值']
            operate_df.loc[mask, '买入累计净值'] = no_one_day_bond_data['累计净值']
            operate_df.loc[mask, '分仓'] = operate_df.loc[mask, '分仓'] + f'被{item["code"]}分仓'
            break
    return operate_df


def sell(bond_df, current_day_bond_data_df, operate_df, current_money):
    for _, item in bond_df.iterrows():
        one_day_bond_data_df = current_day_bond_data_df.loc[current_day_bond_data_df['code'] == item["code"]]
        if one_day_bond_data_df.empty:
            continue
        one_day_bond_data = one_day_bond_data_df.iloc[0]

        mask = (operate_df['code'] == item['code']) & (operate_df['买入时间'].notnull()) & (operate_df['卖出时间'].isnull()) & (operate_df['结束时间'].notnull())
        # if operate_df.loc[mask].empty:
        #     continue
        operate_df.loc[mask, '卖出时间'] = one_day_bond_data['净值日期']
        operate_df.loc[mask, '卖出单位净值'] = one_day_bond_data['单位净值']
        operate_df.loc[mask, '卖出累计净值'] = one_day_bond_data['累计净值']
        operate_df.loc[mask, '持有天数'] = (operate_df.loc[mask, '卖出时间'] - operate_df.loc[mask, '买入时间'])
        operate_df.loc[mask, '收益'] = (one_day_bond_data['累计净值'] - operate_df.loc[mask, '买入累计净值']) * operate_df.loc[mask, '买入数量']
        operate_df.loc[mask, '收益率'] = (one_day_bond_data['累计净值'] - operate_df.loc[mask, '买入累计净值']) / operate_df.loc[mask, '买入单位净值']
        # operate_df.loc[mask, '年收益'] = (one_day_bond_data['累计净值'] - operate_df.loc[mask, '买入累计净值']) / operate_df.loc[mask, '买入单位净值'] / operate_df.loc[mask, '持有天数'].dt.days * 365
        current_money += operate_df.loc[mask, '买入金额'].sum() + operate_df.loc[mask, '收益'].sum()

    return operate_df, current_money


def buy(operate_df, current_day_bond_data_df, current_money, buy_rate, last_day_account):
    # (operate_df['买入时间'].isnull()) &
    mask = (operate_df['卖出时间'].isnull()) & (operate_df['结束时间'].isnull())
    filter_df = operate_df.loc[mask]

    if not filter_df.empty:
        # filter_df = filter_df.sort_values(by='历史最大回撤')
        # filter_df = filter_df.sort_values(by='关注时间', ascending=False)
        filter_df = filter_df.sort_values(by='历史最大回撤')
        for _, item in filter_df.iterrows():
            one_day_bond_data_df = current_day_bond_data_df.loc[current_day_bond_data_df['code'] == item["code"]]
            if one_day_bond_data_df.empty:
                continue
            one_day_bond_data = one_day_bond_data_df.iloc[0]
            if current_money >= buy_rate * last_day_account:
                buy_number = int(buy_rate * last_day_account / one_day_bond_data['单位净值'])
            elif current_money > 10000:
                buy_number = int(current_money / one_day_bond_data['单位净值'])
            else:
                continue
            if pd.notnull(item['买入数量']):
                operate_df = pd.concat([operate_df, pd.DataFrame([{
                    'code': item['code'],
                    '开始时间': item['开始时间'],
                    '关注时间': item['关注时间'],
                    '关注天数': None,
                    '结束时间': None,
                    '历史最大回撤': item['历史最大回撤'],
                    '买入时间': None,
                    '买入金额': None,
                    '买入数量': None,
                    '买入单位净值': None,
                    '买入累计净值': None,
                    '卖出时间': None,
                    '卖出单位净值': None,
                    '卖出累计净值': None,
                    '持有天数': None,
                    '收益': None,
                    '收益率': None,
                    '年收益': None,
                    '分仓': '分仓'
                }])]).reset_index(drop=True)
            mask = (operate_df['code'] == item['code']) & (operate_df['买入时间'].isnull()) & (operate_df['卖出时间'].isnull()) & (operate_df['结束时间'].isnull())
            operate_df.loc[mask, '买入时间'] = one_day_bond_data['净值日期']
            operate_df.loc[mask, '买入金额'] = one_day_bond_data['单位净值'] * buy_number
            operate_df.loc[mask, '买入数量'] = buy_number
            operate_df.loc[mask, '买入单位净值'] = one_day_bond_data['单位净值']
            operate_df.loc[mask, '买入累计净值'] = one_day_bond_data['累计净值']
            current_money -= one_day_bond_data['单位净值'] * buy_number
    return operate_df, current_money


def buy_no_buy(operate_df, current_day_bond_data_df, current_money, buy_rate, last_day_account):
    mask = (operate_df['买入时间'].isnull()) & (operate_df['卖出时间'].isnull()) & (operate_df['结束时间'].isnull())
    filter_df = operate_df.loc[mask]

    if not filter_df.empty:
        filter_df = filter_df.sort_values(by='历史最大回撤')
        # filter_df = filter_df.sort_values(by='关注时间', ascending=False)
        for _, item in filter_df.iterrows():
            one_day_bond_data_df = current_day_bond_data_df.loc[current_day_bond_data_df['code'] == item["code"]]
            if one_day_bond_data_df.empty:
                continue
            one_day_bond_data = one_day_bond_data_df.iloc[0]
            if current_money >= buy_rate * last_day_account:
                buy_number = int(buy_rate * last_day_account / one_day_bond_data['单位净值'])
            elif current_money > 10000:
                buy_number = int(current_money / one_day_bond_data['单位净值'])
            else:
                continue
            if pd.notnull(item['买入数量']):
                operate_df = pd.concat([operate_df, pd.DataFrame([{
                    'code': item['code'],
                    '开始时间': item['开始时间'],
                    '关注时间': item['关注时间'],
                    '关注天数': None,
                    '结束时间': None,
                    '历史最大回撤': item['历史最大回撤'],
                    '买入时间': None,
                    '买入金额': None,
                    '买入数量': None,
                    '买入单位净值': None,
                    '买入累计净值': None,
                    '卖出时间': None,
                    '卖出单位净值': None,
                    '卖出累计净值': None,
                    '持有天数': None,
                    '收益': None,
                    '收益率': None,
                    '年收益': None,
                    '分仓': '分仓'
                }])]).reset_index(drop=True)
            mask = (operate_df['code'] == item['code']) & (operate_df['买入时间'].isnull()) & (operate_df['卖出时间'].isnull()) & (operate_df['结束时间'].isnull())
            operate_df.loc[mask, '买入时间'] = one_day_bond_data['净值日期']
            operate_df.loc[mask, '买入金额'] = one_day_bond_data['单位净值'] * buy_number
            operate_df.loc[mask, '买入数量'] = buy_number
            operate_df.loc[mask, '买入单位净值'] = one_day_bond_data['单位净值']
            operate_df.loc[mask, '买入累计净值'] = one_day_bond_data['累计净值']
            current_money -= one_day_bond_data['单位净值'] * buy_number
    return operate_df, current_money


def update_account(operate_df, account_df, current_day_bond_data_df, current_time, current_money):
    total_cost = 0
    total_profit_loss = 0
    total_number = 0
    mask = (operate_df['买入时间'].notnull()) & (operate_df['卖出时间'].isnull())
    filter_df = operate_df.loc[mask]
    if not filter_df.empty:
        for _, item in filter_df.iterrows():
            one_day_bond_data_df = current_day_bond_data_df.loc[current_day_bond_data_df['code'] == item["code"]]
            if one_day_bond_data_df.empty:
                continue
            one_day_bond_data = one_day_bond_data_df.iloc[0]
            total_cost += item['买入金额']
            total_profit_loss = (one_day_bond_data['累计净值'] - item['买入累计净值']) * item['买入数量']
            total_number += 1
    account_df = pd.concat([account_df, pd.DataFrame([{
        '日期': current_time,
        '策略': '',
        '总资产': current_money + total_cost + total_profit_loss,
        '现金余额': current_money,
        '持仓市值': total_cost + total_profit_loss,
        '持仓成本': total_cost,
        '持仓盈亏': total_profit_loss,
        '持仓数量': total_number
    }])]).reset_index(drop=True)
    return account_df

